<?php
namespace app\agent\service;

use app\agent\logic\StatisticsBankLogic;
use app\agent\logic\StatisticsTurnoverLogic;
use app\agent\logic\UserAgentLogic;
use app\agent\logic\UserLogic;
use app\agent\logic\UserPaydetalisAgentLogic;
use app\agent\logic\WkSellerexLogic;
use app\agent\logic\WkSellerLogic;
use app\agent\servlet\UserAgentServlet;
use think\Db;

class UserAgentService extends BaseService
{
	private $userAgent = null;
	
	private $servlet = null;

	private $statisticsTurnover = null;

	private $statisticsBank = null;

	private $wkSeller = null;

	private $wkSellerex = null;

	private $user = null;

	private $userPaydetalisAgent = null;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->userAgent = new UserAgentLogic();
		
		$this->servlet = new UserAgentServlet();

		$this->statisticsTurnover = new StatisticsTurnoverLogic();

		$this->statisticsBank = new StatisticsBankLogic();

		$this->wkSeller = new WkSellerLogic();

		$this->wkSellerex = new WkSellerexLogic();

        $this->user = new UserLogic();

        $this->userPaydetalisAgent = new UserPaydetalisAgentLogic();
	}

	/**
	* @action 代理商后台详情
	*/
	public function getViewDetail($data = [])
	{
		$where = [
		    $this->userAgent->getPk() => $data['id'],
		];

		$data = $this->userAgent->getDetail($where);

		if ( $data === false )
		{
			$this->error = $this->userAgent->getError();

			return false;
		}

		return $data;
	}

    public function login($data)
    {
        //获取user信息并验证
        $user = $this->userAgent->login($data);

        if( $user === false )
        {
            $this->error = $this->userAgent->getError();

            return false;
        }

        //保存登录信息
        $this->servlet->login($user);

        return true;
	}

    public function freeLogin($request)
    {
        //获取user信息
        $user = $this->userAgent->freeLogin($request['uid']);

        if( empty($user) )
        {
            $this->error = '代理商不存在!';

            return false;
        }

        //保存登录信息
        $this->servlet->login($user);

        return true;
	}

    /**
     * 获取首页数据
     * @param $data
     */
    public function home($request)
    {
        //获取辖区商家数量
        $data['sellers'] = $this->wkSellerex->getSellerexByType($request['type'], $request['addr_code']);

        //getWhere
        $type = $this->wkSeller->_map['type'][$request['type']];
        $where = [
            [$type, '=', $request['addr_code']],
            ['ytime', '=', date('Y', time())],
        ];

        //获取辖区商家积分营业额
        $data['turnovers'] = $this->wkSeller->getSellersProfit($where, $this->statisticsTurnover);

        //获取辖区商家现金营业额
        $data['bank'] = $this->wkSeller->getSellersProfit($where, $this->statisticsBank);

        //获取代理商今日收益
        $config         = "agent.{$request['type']}";
        $data['profit'] = sprintf("%.2f", ($data['turnovers']['pday'] + $data['bank']['pday']) * config($config));

        return $data;
	}

    public function getZhuanchuView($request)
    {
        $where = $this->servlet->getWhere($request);

        $userAgent = $this->userAgent->where($where)->find();

        return $userAgent;
	}

    public function zhuanchu($request)
    {
        $where = $this->servlet->getWhere($request);

        //验证24小时内是否转出过
        if( empty($this->userPaydetalisAgent->checkZhuanchu($request)) === false )
        {
            $this->error = '24小时内只能转出一次';

            return false;
        }

        //获取userAgent模型对象
        $userAgent = $this->userAgent->where($where)->find();
        //减钱
        $userAgent->agent_money = bcsub($userAgent->agent_money, $request['turn_money']);

        //判断钱为负数
        if( $userAgent->agent_money < 0 )
        {
            $this->error = '余额不足';

            return false;
        }

        //获取user模型对象
        $user = $this->user->where($where)->find();
        //加钱
        $user->money = bcadd($user->money, $request['turn_money']);

        //事务控制
        Db::startTrans();
        try{
            //保存
            $userAgent->save();
            $user->save();

            Db::commit();
        } catch (\Exception $e) {
            //回滚
            Db::rollback();

            $this->error = '转出失败!';

            return false;
        }

        //添加减钱记录
        $record_agent = [
            'uid'        => $request['uid'],
            'fromuid'    => $request['uid'],
            'value'      => $request['turn_money'],
            'aftervalue' => $userAgent->agent_money,
            'type'       => 2,
            'paytype'    => 2,
            'status'     => 1,
            'orderid'    => create_order_no(2),
            'oktime'     => date('Y-m-d H:i:s', time()),
        ];
        db('user_paydetalis_agent')->insert($record_agent);

        //添加加钱记录
        $record = [
            'uid'      => $request['uid'],
            'typeid'   => 2,
            'orderid'  => create_order_no(2),
            'value'    => $request['turn_money'],
            'gouwu'    => $user->money,
            'type'     => '代理商积分转出',
            'ispay'    => 2,
            'datetime' => time(),
        ];

        db('user_paydetails')->insert($record);

        return true;
	}
}